package cn.sdhuijin.healthexam.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import cn.sdhuijin.healthexam.DatabaseHelper;
import cn.sdhuijin.healthexam.ExitApplication;
import cn.sdhuijin.healthexam.R;
import cn.sdhuijin.healthexam.adapter.ExListViewAdapter;
import cn.sdhuijin.healthexam.bean.OrganizationData;
import cn.sdhuijin.healthexam.bean.UserData;
import cn.sdhuijin.healthexam.util.Util;

public class ManagementActivity extends AbstractActivity implements
		OnClickListener {
	private ExpandableListView mListView;
	ExListViewAdapter adapter;
	private DatabaseHelper databaseHelper;
	private EditText etId, etName, etUserName, etPassword;
	private Button btOk, btNo;
	private Dialog dialogAdd;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_management);
		ExitApplication.getInstance().addActivity(this);

		databaseHelper = new DatabaseHelper(this);
		mListView = (ExpandableListView) findViewById(R.id.ex_listview);
		setButtonListener(this, R.id.btn_add, R.id.btn_update,
				R.id.btn_update_pwd, R.id.btn_exit);
		init();
	}

	/**
	 * 数据初始化
	 */
	private void init() {
		List<OrganizationData> tempGroup = databaseHelper.searchOrganization();

		List<ArrayList<UserData>> cDatas = new ArrayList<ArrayList<UserData>>();
		ArrayList<UserData> list = null;
		for (int i = 0; i < tempGroup.size(); i++) {
			list = (ArrayList<UserData>) databaseHelper.searchUser(tempGroup
					.get(i).getId());
			cDatas.add(list);
		}
		adapter = new ExListViewAdapter(this, tempGroup, cDatas, this);
		mListView.setAdapter(adapter);
		// 展开
		int groupCount = mListView.getCount();
		for (int i = 0; i < groupCount; i++) {
			mListView.expandGroup(i);
		}

	}

	@Override
	public void onClick(final View v) {
		Intent intent = new Intent();
		int clickId = v.getId();
		switch (clickId) {
		case R.id.group_rightbtn:
			String tags = v.getTag().toString();
			OrganizationData gdata = adapter.grouDatas.get(Integer
					.parseInt(tags));
			Log.i("TAG", tags);
			createDialogAdd(gdata.getId());
			dialogAdd.show();
			break;
		case R.id.group_delete_btn:
			new AlertDialog.Builder(this)
					.setTitle("提示")
					.setMessage("确定删除?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									int deleteIndex = Integer.parseInt(v
											.getTag().toString());
									databaseHelper
											.deleteOrganization(adapter.grouDatas
													.get(deleteIndex).getId());
									adapter.grouDatas.remove(deleteIndex);
									adapter.notifyDataSetChanged();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
			break;
		case R.id.group_update_name_btn:
			int updateNameIndex = Integer.parseInt(v.getTag().toString());
			updateOrganizationName(adapter.grouDatas.get(updateNameIndex)
					.getId());
			dialogAdd.show();
			break;
		case R.id.btn_add:
			addOrganization();
			dialogAdd.show();
			break;
		case R.id.btn_exit:
			this.finish();
			break;
		case R.id.child_update_pwd_btn:
			String[] tempChildTag = v.getTag().toString().split(",");
			int groupIndex = Integer.parseInt(tempChildTag[0]);
			int childIndex = Integer.parseInt(tempChildTag[1]);
			updatePwd(adapter.userDatas.get(groupIndex).get(childIndex)
					.getUserName());
			dialogAdd.show();
			break;
		case R.id.child_rightbtn:
			new AlertDialog.Builder(this)
					.setTitle("提示")
					.setMessage("确定删除?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String[] temptag = v.getTag().toString()
											.split(",");
									int gIndex = Integer.parseInt(temptag[0]);
									int cIndex = Integer.parseInt(temptag[1]);
									databaseHelper.deleteUser(adapter.userDatas
											.get(gIndex).get(cIndex)
											.getUserName());
									adapter.userDatas.get(gIndex)
											.remove(cIndex);
									adapter.notifyDataSetChanged();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
			break;
		case R.id.btn_update_pwd:
			intent.setClass(this, UpdatePWDActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_update:
			intent.setClass(this, UpdateActivity.class);
			startActivity(intent);
			break;

		}
	}

	/**
	 * 添加医务人员Dialog
	 * 
	 * @param id
	 *            机构编号
	 */
	private void createDialogAdd(final String id) {
		View viewAdd = this.getLayoutInflater().inflate(R.layout.dialog_user,
				null);
		dialogAdd = new Dialog(this);
		dialogAdd.setContentView(viewAdd);
		dialogAdd.setTitle("添加医务人员");
		etId = (EditText) viewAdd.findViewById(R.id.edt_id);
		etUserName = (EditText) viewAdd.findViewById(R.id.edt_user_name);
		etPassword = (EditText) viewAdd.findViewById(R.id.edt_password);
		btOk = (Button) viewAdd.findViewById(R.id.btn_save);
		btNo = (Button) viewAdd.findViewById(R.id.btn_cancel);
		btOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String userid = etId.getText().toString().trim();
				String userName = etUserName.getText().toString().trim();
				String password = etPassword.getText().toString().trim();
				if (Util.allIsNotEmpty(userName, password)) {
					if (databaseHelper.userIsExits(userName)) {
						ManagementActivity.this
								.toastInformation(R.string.user_exists);
					} else {
						databaseHelper.insertDataToUser(userid, userName,
								password, id);
						dialogAdd.dismiss();
						adapter.notifyDataSetChanged();
						Intent intent = new Intent();
						intent.setClass(ManagementActivity.this,
								ManagementActivity.class);
						startActivity(intent);
						ManagementActivity.this.finish();
					}
				} else {
					ManagementActivity.this
							.toastInformation(R.string.login_input_not_null);
				}
			}
		});
		btNo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogAdd.dismiss();
			}
		});
	}

	/**
	 * 创建添加机构Dialog
	 */
	private void addOrganization() {
		View viewAdd = this.getLayoutInflater().inflate(
				R.layout.dialog_organization, null);
		dialogAdd = new Dialog(this);
		dialogAdd.setContentView(viewAdd);
		dialogAdd.setTitle("添加机构");
		etName = (EditText) viewAdd.findViewById(R.id.edt_name);
		btOk = (Button) viewAdd.findViewById(R.id.btn_save);
		btNo = (Button) viewAdd.findViewById(R.id.btn_cancel);
		btOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = etName.getText().toString().trim();
				if (Util.allIsNotEmpty(name)) {
					databaseHelper.insertDataToOrganization(name);
					dialogAdd.dismiss();
					adapter.notifyDataSetChanged();
					Intent intent = new Intent();
					intent.setClass(ManagementActivity.this,
							ManagementActivity.class);
					startActivity(intent);
					ManagementActivity.this.finish();
				} else {
					ManagementActivity.this
							.toastInformation(R.string.name_not_null);
				}
			}
		});
		btNo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogAdd.dismiss();
			}
		});
	}

	/**
	 * 创建修改机构名称Dialog
	 */
	private void updateOrganizationName(final String OrganizationId) {
		View viewAdd = this.getLayoutInflater().inflate(
				R.layout.dialog_update_organization_name, null);
		dialogAdd = new Dialog(this);
		dialogAdd.setContentView(viewAdd);
		dialogAdd.setTitle("修改机构名称");
		etName = (EditText) viewAdd.findViewById(R.id.edt_organization_name);
		btOk = (Button) viewAdd.findViewById(R.id.btn_save);
		btNo = (Button) viewAdd.findViewById(R.id.btn_cancel);
		btOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = etName.getText().toString().trim();
				if (Util.allIsNotEmpty(name)) {
					databaseHelper.updateOrganizationName(OrganizationId, name);
					dialogAdd.dismiss();
					adapter.notifyDataSetChanged();
					Intent intent = new Intent();
					intent.setClass(ManagementActivity.this,
							ManagementActivity.class);
					startActivity(intent);
					ManagementActivity.this.finish();
					ManagementActivity.this
							.toastInformation(R.string.organization_name_update_success);
				} else {
					ManagementActivity.this
							.toastInformation(R.string.organization_name_not_null);
				}
			}
		});
		btNo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogAdd.dismiss();
			}
		});
	}

	/**
	 * 创建重置密码Dialog
	 */
	private void updatePwd(final String userName) {
		View viewAdd = this.getLayoutInflater().inflate(
				R.layout.dialog_update_password, null);
		dialogAdd = new Dialog(this);
		dialogAdd.setContentView(viewAdd);
		dialogAdd.setTitle("重置密码");
		etPassword = (EditText) viewAdd.findViewById(R.id.edt_password);
		btOk = (Button) viewAdd.findViewById(R.id.btn_save);
		btNo = (Button) viewAdd.findViewById(R.id.btn_cancel);
		btOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String password = etPassword.getText().toString().trim();
				if (Util.allIsNotEmpty(password)) {
					databaseHelper.updateUserPassword(userName, password);
					dialogAdd.dismiss();
					adapter.notifyDataSetChanged();
					ManagementActivity.this
							.toastInformation(R.string.update_pwd_success);
				} else {
					ManagementActivity.this
							.toastInformation(R.string.password_not_null);
				}
			}
		});
		btNo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialogAdd.dismiss();
			}
		});
	}
}
